<template>
  <div class="address-list">
    <ul class="list" v-if="list.length > 0">
      <li
        v-for="(item, index) in list"
        :key="index"
        class="list-item"
      >
        <address-item
          :info="item"
          @removeAddress="removeAddress"
          @changeDefault="changeDefault"
        />
      </li>
    </ul>
    <div v-else class="nothing">
      暂无地地址,请先添加
    </div>
    <footer-button
      icon="cubeic-add"
      text="添加新地址"
      @submit="createAddress"
    />
    <loading :show="loading" />
  </div>
</template>

<script>
import FooterButton from './components/FooterButton'
import AddressItem from './components/AddressItem'
import api from '@/api'
import Loading from '@/components/Loading'
export default {
  name: 'AddressList',
  components: {
    FooterButton,
    AddressItem,
    Loading
  },
  data() {
    return {
      list: [],
      loading: false
    }
  },
  methods: {
    async getList() {
      this.loading = true
      const { data } = await api.Address.list()
      this.list = data
      this.loading = false
    },
    // create
    createAddress() {
      this.$router.push('/service/address-edit')
    },
    // remove
    removeAddress(id) {
      this.loading = true
      api.Address.remove({ id }).then(() => {
        this.$createToast({
          type: 'txt',
          txt: '操作成功',
          time: 500,
          onTimeout: () => {
            this.list = this.list.filter(x => x.id !== id)
          }
        }).show()
      }).finally(() => {
        this.loading = false
      })
    },
    // changeDefault
    changeDefault(options) {
      /*
        这里会请求多次(2次,1个开,1个关),
        forEach改变了is_default值,子组件AddressItem都会同时改变
        因为子组件会监听状态改变,都会emit过来,
        所以这里弹窗只显示"开启"的
       */
      const [id, value] = options
      this.loading = true
      api.Address.setDefault({ id, value }).then(() => {
        if (value === '1') {
          this.$createToast({
            type: 'txt',
            txt: '操作成功',
            time: 500,
            onTimeout: () => {
              this.list.forEach(x => {
                if (x.id !== id) {
                  x.is_default = '0'
                }
              })
            }
          }).show()
        }
      }).finally(() => {
        this.loading = false
      })
    }
  },
  created () {
    this.getList()
  }
}
</script>

<style scoped lang="stylus">
.address-list
  background $background_color
  min-height 600px
  .nothing
    margin-top 20px
</style>
